package com.socket;

import com.fazecast.jSerialComm.SerialPort;

import java.util.Scanner;

public class SendAT {
    public static void main(String[] args) throws InterruptedException {
        SerialPort serialPort = set();
        if(serialPort != null) {
           // open(serialPort);
            close(serialPort);
            serialPort.closePort();
        }else{
            System.out.println("串口未打开");
        }

    }

    public static SerialPort set() throws InterruptedException {
        SerialPort[] ports = SerialPort.getCommPorts();
        System.out.println("选择串口:");
        for (int i = 0; i < ports.length; i++) {
            System.out.println(i + ": " + ports[i].getSystemPortName());
        }
        Scanner sc = new Scanner(System.in);
        int i = sc.nextInt();
        // 手动选择一个串口（比如 UART1 对应 COM4）
        SerialPort serialPort = ports[i]; // 改成你实际使用的端口号索引

        if (serialPort.openPort()) {
            System.out.println("Port opened successfully.");
            serialPort.setComPortParameters(115200, 8, 1, 0); // 波特率等参数根据Hi3867配置调整
            serialPort.setComPortTimeouts(SerialPort.TIMEOUT_WRITE_BLOCKING, 0, 0);

            String atCommand1 = "AT+SETIOMODE=9,0,0,3\r\n"; // 示例指令
            byte[] data1 = atCommand1.getBytes();
            serialPort.writeBytes(data1, data1.length);
            System.out.print("Sent: " + atCommand1);

            Thread.sleep(1000);
            String atCommand2 = "AT+GPIODIR=9,1\r\n"; // 示例指令
            byte[] data2 = atCommand2.getBytes();
            serialPort.writeBytes(data2, data2.length);
            System.out.print("Sent: " + atCommand2);



            return serialPort;
        } else {
            System.out.print("Failed to open port.");
            return null;
        }
    }

    public static void open(SerialPort serialPort) throws InterruptedException {
        Thread.sleep(1000);
        String atCommand3 = "AT+WTGPIO=9,0\r\n"; // 示例指令
        byte[] data3 = atCommand3.getBytes();
        serialPort.writeBytes(data3, data3.length);
        System.out.print("Sent: " + atCommand3);
    }

    public static void close(SerialPort serialPort) throws InterruptedException {
        Thread.sleep(1000);
        String atCommand3 = "AT+WTGPIO=9,1\r\n"; // 示例指令
        byte[] data3 = atCommand3.getBytes();
        serialPort.writeBytes(data3, data3.length);
        System.out.print("Sent: " + atCommand3);
    }
}